package com.hunan.api.catv.mq.consumer;

import com.google.gson.JsonObject;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.service.biz.system.SystemDictBiz;
import com.hunan.api.catv.service.impl.function.remote.RemoteControlService;
import com.hunan.api.catv.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author wangchao
 * @date 2021-05-31 4:10 下午
 */
@Component
public class UntieRemoteConsumer {

    public static Logger log = LoggerFactory.getLogger(UntieRemoteConsumer.class);

    @Autowired
    SystemDictBiz systemDictBiz;

    @Autowired
    RemoteControlService remoteControlService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConstants.UNTIE_REMOTE_QUEUE, durable = "true"), exchange = @Exchange(value = MqConstants.UNTIE_REMOTE_EXCHANGE, durable = "true", type = "topic"), key = MqConstants.UNTIE_REMOTE_ROUTINGKEY))
    public void tasks(String phone) {
        log.info("用户解绑遥控器 {} ]", phone);
        String key = systemDictBiz.getStringByKey(Constants.remote_control_config);
        JsonObject jsonObject = GsonUtils.fromJson(key, JsonObject.class);
        String domain = jsonObject.get("domain").getAsString();
        String appId = jsonObject.get("appId").getAsString();
        String secretKey = jsonObject.get("secretKey").getAsString();
        //获取服务商遥控器token
        String accessToken = null;
        try {
            accessToken = getAccessToken(domain, appId, secretKey);
            if (accessToken != null) {
                //解绑设备
                JsonObject jsonObject1 = remoteControlService.untieEquipment(domain, phone, accessToken);
            }
        } catch (Exception e) {
            log.error("解绑错误：{}", e);
        }
        log.info("用户解绑结束:{}", System.currentTimeMillis());
    }

    private String getAccessToken(String domain, String appId, String secretKey) {
        HashMap<String, String> map = new HashMap<>(16);
        map.put("appId", appId);
        map.put("secretKey", secretKey);
        String accessToken = remoteControlService.getAccessToken(domain, map);
        return accessToken;
    }
}
